import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/login/Login.vue";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: "/",
            name: "home",
            component: HomeView,
            //重定向到登录页面
            redirect: "/login",
        },
        {
            path: "/login",
            name: "login",
            component: () => import("../views/login/Login.vue"),
        },
        //AdminView
        {
            path: "/admin",
            name: "admin",
            component: () => import("../views/admin/AdminView.vue"),
        },
        // 注册页面
        {
            path: "/register",
            name: "register",
            component: () => import("../views/login/Register.vue"),
        },
        // 修改密码页面
        {
            path: "/changePassword",
            name: "changePassword",
            component: () => import("../views/login/ChangePassword.vue"),
        },

        //ManageView
        {
            path: "/traffic",
            name: "traffic",
            component: () => import("../views/traffic/TrafficView.vue"),
        },
        //NormalView
        {
            path: "/normal",
            name: "normal",
            component: () => import("../views/normal/NormalView.vue"),
        },
    ],
});

const nextMap = {
    admin: "admin",
    normal: "normal",
    traffic: "traffic",
};

// 路由守卫
router.beforeEach((to, from, next) => {
    // 登录页面直接放行
    if (to.name === "login"||to.name === "register"|to.name === "changePassword") {
        next();
    } else {
        // 其他页面需要登录
        const token = localStorage.getItem("token");
        // const userDataStr = localStorage.getItem("userData");
        // if (!userDataStr || token === null) {
        //     next({ name: "login" });
        // } else {
        //     console.log('userDataStr:');
        //     const userData = JSON.parse(userDataStr);
        //     next({ name: nextMap[userData.type] });
        // }

        if (token) {
            next();
        } else {
            next({ name: "login" });
        }
    }
});

export default router;
